package controller

import (
	"errors"
	"mini-app/config/mysql"
	"mini-app/internal/app/admin/service"
	"mini-app/internal/app/grpc/client"
	"mini-app/internal/app/grpc/protoc/system_admin"
	"mini-app/internal/dao"
	"mini-app/internal/models"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
	"192.168.1.75/go-pkg/logx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

/*
	{
		rg.POST("/puppet-user/puppet-user-edit", controller.PuppetUser{}.Edit)     // 编辑
		rg.GET("/puppet-user/puppet-user-list", controller.PuppetUser{}.List)      // 列表
		rg.POST("/puppet-user/puppet-user-create", controller.PuppetUser{}.Create) // 新增
		rg.POST("/puppet-user/puppet-user-update", controller.PuppetUser{}.Update) // 更新
		rg.GET("/puppet-user/puppet-user-detail", controller.PuppetUser{}.Detail)  // 详情
		rg.POST("/puppet-user/puppet-user-delete", controller.PuppetUser{}.Delete) // 新增
	}
*/
type PuppetUser struct {
	PuppetUserSvr service.PuppetUser
}

// Update 更新
func (t PuppetUser) Edit(c *gin.Context) {
	var err error

	var params struct {
		ID       int64  `json:"id,string"`
		NickName string `json:"nick_name"`
		Avatar   string `json:"avatar"`
		Gender   int    `json:"gender"`
	}

	err = c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errors.Join(errors.New("参数错误"), err))
		return
	}

	var avatarSaved string = params.Avatar
	{

		if params.Avatar != "" {
			rc, err := t.PuppetUserSvr.Detail(c.Request.Context(), dao.PuppetUserFilter{
				ID: params.ID,
			})
			if err != nil {
				logx.Error(c.Request.Context(), "PuppetUser.Edit detail error", logx.Any("rc", rc), logx.Any("err", err))
				err = errorx.New(errors.Join(errors.New("查询记录失败"), err).Error(), -1)
				response.JSON(c, nil, err)
				return
			}

			if rc != nil && params.Avatar != rc.Avatar {
				SystemAdminClient, clientErr := client.GetSystemAdminClient()
				if clientErr != nil {
					err = clientErr
					response.JSON(c, nil, err)
					return
				}

				var req system_admin.ConfirmFileReq
				req.FileUrl = params.Avatar
				res, err1 := SystemAdminClient.ConfirmFile(c.Request.Context(), &req)
				if err1 != nil && res.Code != 0 {
					logx.Error(c.Request.Context(), "PuppetUser.Edit confirm file error", logx.Any("res", res), logx.Any("err", err1.Error()))
					err = errorx.New("保存图片失败", -1)
					response.JSON(c, nil, err)
					return
				}
				avatarSaved = res.FileUrl
			}

		}
	}

	var rc models.PuppetUser
	if params.ID == 0 {

		rc.NickName = params.NickName
		rc.Avatar = avatarSaved
		rc.Gender = params.Gender

		err = t.PuppetUserSvr.Create(c.Request.Context(), &rc)
		if err != nil {
			response.JSON(c, nil, err)
			return
		}

	} else {
		rc.ID = params.ID
		rc.NickName = params.NickName
		rc.Avatar = avatarSaved
		rc.Gender = params.Gender

		err = t.PuppetUserSvr.Update(c.Request.Context(), &rc)
		if err != nil {
			response.JSON(c, nil, err)
			return
		}
	}

	response.JSON(c, gin.H{
		"id": rc.ID,
	}, err)
}

// Create 新增
func (t PuppetUser) Create(c *gin.Context) {
	var params struct {
		NickName string `json:"nick_name" binding:"required"`
		Avatar   string `json:"avatar"`
		Gender   int    `json:"gender"`

		//WinCount int    `json:"win_count"`
	}
	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errors.Join(errors.New("参数错误"), err))
		return
	}

	var rc models.PuppetUser
	rc.NickName = params.NickName
	rc.Avatar = params.Avatar
	rc.Gender = params.Gender

	err = t.PuppetUserSvr.Create(c.Request.Context(), &rc)
	if err != nil {
		response.JSON(c, nil, err)
		return
	}
	response.JSON(c, gin.H{
		"id": rc.ID,
	}, err)
}

// Update 更新
func (t PuppetUser) Update(c *gin.Context) {
	var params struct {
		ID       int64  `json:"id,string"`
		NickName string `json:"nick_name"`
		Avatar   string `json:"avatar"`
		Gender   int    `json:"gender"`
	}

	err := c.ShouldBindBodyWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errors.Join(errors.New("参数错误"), err))
		return
	}

	var rc models.PuppetUser
	rc.ID = params.ID
	rc.NickName = params.NickName
	rc.Avatar = params.Avatar
	rc.Gender = params.Gender

	err = t.PuppetUserSvr.Update(c.Request.Context(), &rc)

	response.JSON(c, nil, err)
}

// Detail
func (t PuppetUser) Detail(c *gin.Context) {
	var params struct {
		ID int64 `form:"id,string"`
	}
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		response.JSON(c, nil, errors.Join(errors.New("参数错误"), err))
		return
	}

	var filter dao.PuppetUserFilter
	filter.ID = params.ID
	detail, err := t.PuppetUserSvr.Detail(
		c.Request.Context(),
		filter,
	)
	response.JSON(c, detail, err)
}

// Delete 删除
func (t PuppetUser) Delete(c *gin.Context) {
	var params struct {
		ID int64 `json:"id,string"`
	}
	err := c.ShouldBindWith(&params, binding.JSON)
	if err != nil {
		response.JSON(c, nil, errors.Join(errors.New("参数错误"), err))
		return
	}

	if params.ID == 0 {
		response.JSON(c, nil, errors.New("参数错误:id不能为空"))
		return
	}

	var filter dao.PuppetUserFilter
	filter.ID = params.ID
	err = t.PuppetUserSvr.DeleteById(c.Request.Context(), params.ID)
	response.JSON(c, nil, err)
}

func (t PuppetUser) List(c *gin.Context) {
	var params struct {
		Page  int `form:"page" binding:"required"`
		Limit int `form:"limit" binding:"required"`

		// 未被选中且返回随机记录，这个数值表示返回的记录数，0表示这个条件无效,非0表示返回几个符合该条件的记录
		FilterNumOfRandomUser int    `form:"filter_num_of_random_user"` //返回随机的马甲用户数据
		FilterNickName        string `form:"nick_name"`
		ActivityId            string `form:"activity_id"`
	}
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		response.JSON(c, nil, errors.Join(errors.New("参数错误"), err))
		return
	}

	var resultList []*models.PuppetUser
	var total int64
	if params.FilterNumOfRandomUser != 0 {
		if params.ActivityId == "" {
			response.JSON(c, nil, errors.New("参数错误: 随机查询时activity_id不能为空"))
			return
		}
		if params.FilterNumOfRandomUser > 1000 {
			response.JSON(c, nil, errors.New("参数错误: 随机查询数量不能超过1000"))
			return
		}
		resultList, total, err = t.PuppetUserSvr.ListRandomPuppetUser(c.Request.Context(), params.ActivityId, params.FilterNumOfRandomUser)
		if err != nil {
			response.JSON(c, nil, err)
			return
		}
	} else {
		// 参数验证
		if params.Page <= 0 {
			response.JSON(c, nil, errors.New("参数错误: page必须大于0"))
			return
		}
		if params.Limit <= 0 {
			response.JSON(c, nil, errors.New("参数错误: limit必须大于0"))
			return
		}
		filter := dao.PuppetUserListFilter{
			NickName: params.FilterNickName,
		}
		page := helper.NewPageInfo(int64(params.Page), int64(params.Limit), nil)

		resultList, total, err = t.PuppetUserSvr.List(c.Request.Context(), page, filter)
		if err != nil {
			response.JSON(c, nil, err)
			return
		}

		for _, record := range resultList {
			record.WinCount = int(dao.OnlineEventUser{}.WinCount(c.Request.Context(), mysql.NewDB(), helper.Int64ToString(record.ID)))
		}

	}

	response.JSON(c, gin.H{
		"list":  resultList,
		"total": total,
	}, err)
}
